package spider

import (
	"encoding/json"
	//	"fmt"
	"io/ioutil"
	"priceApi/models"
	"priceApi/utils"

	//"strconv"
	//"time"

	"github.com/astaxie/beego"
)

type HuobiUsdtData struct {
	Price      float64 `json:"price"`
	TradeCount float64 `json:"tradeCount`
}

type HuobiUsdt struct {
	Code int64           `json:"code"`
	Data []HuobiUsdtData `json:"data"`
}

func GetHuobiUsdtPrice(Type string) float64 {
	var jsondata HuobiUsdt

	resp, err := utils.GetBySS("https://otc-api.hbg.com/v1/data/trade-market?country=37&currency=1&payMethod=0&currPage=1&coinId=2&tradeType=" + Type + "&blockType=general&online=1")

	if err != nil {
		utils.PostError("获取huobi USDT出错,resp, err := client.Do(req)", err.Error())
		return 0
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	//fmt.Println(string(body))
	if err != nil {
		utils.PostError("获取huobi USDT出错,body, err := ioutil.ReadAll(resp.Body)", err.Error())
		return 0
	}
	json.Unmarshal([]byte(body), &jsondata)
	beego.Debug("获取huobi USDT", jsondata)
	if jsondata.Code == 200 {
		var count, sum float64
		for _, v := range jsondata.Data {
			sum = sum + v.Price*v.TradeCount
			count = count + v.TradeCount
		}
		return sum / count
	} else {
		utils.PostError("获取huobi USDT出错,jsondata.Code == 200", "jsondata.Code != 200")
		return 0
	}
	return 0
}

func GetRmbtPrice() {
	//	rate := GetAliyunRate()
	//	usdtbuy := GetHuobiUsdtPrice("buy")
	//	time.Sleep(time.Second * 3)
	//	usdtsell := GetHuobiUsdtPrice("sell")
	//	if usdtbuy <= 0 || usdtsell <= 0 {
	//		beego.Debug("获取GetRmbtPrice错误", usdtbuy, usdtsell)
	//		utils.PostError("获取GetRmbtPrice错误", "数据为零")
	//		return
	//	}
	//	rmbtbuy := usdtbuy / rate
	//	rmbtsell := usdtsell / rate

	//	v1, _ := strconv.ParseFloat(strconv.FormatFloat((rmbtbuy+rmbtsell)/2, 'f', 2, 64), 64)

	models.InsertPrice(3, "URMB", 1, 1)
}
